package cn.example.vip.mall.search.util;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.ByteBufferReference;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.DefaultResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.util.Map;

@Component
public class HighlightResultMapper extends DefaultResultMapper {
	/**
	 * 映射转换
	 * @param response
	 * @param clazz
	 * @param pageable
	 * @return
	 * @param <T>
	 */
	@Override
	public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
		// 获取所有命中的数据集合
		for(SearchHit hit : response.getHits()) {
			// 获取原数据
			Map<String, Object> sourceMap = hit.getSourceAsMap();
			// 获取命中的高亮数据
			for(Map.Entry<String, HighlightField> entry : hit.getHighlightFields().entrySet()){
				String key = entry.getKey();
				// 将非高亮数据替换成高亮数据
				if(sourceMap.containsKey(key)){
					Text[] fragments = entry.getValue().getFragments();
					sourceMap.put(key, transTextArrayToString(fragments));
				}
			}
			hit.sourceRef(
				new ByteBufferReference(
					ByteBuffer
						.wrap(JSONObject
								.toJSONString(sourceMap)
								.getBytes())));
		}
		
		return super.mapResults(response, clazz, pageable);
	}
	
	/**
	 * 拼接数据碎片
	 */
	private String transTextArrayToString(Text[] fragments) {
		if (null == fragments) {
			return "";
		}
		StringBuilder buffer = new StringBuilder();	// java 8 推荐使用StringBuilder
		for (Text fragment : fragments) {
			buffer.append(fragment.string());
		}
		return buffer.toString();
	}
	
}
